package com.dn.lotte.ui.mainFragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dn.lotte.R;
import com.dn.lotte.api.UserCenterServerApi;
import com.dn.lotte.app.GlobalApplication;
import com.dn.lotte.bean.EventBusBean;
import com.dn.lotte.bean.KefuBean;
import com.dn.lotte.bean.SetSafequesBean;
import com.dn.lotte.bean.TimeBean;
import com.dn.lotte.ui.usercenter.activity.AccountActivity;
import com.dn.lotte.ui.usercenter.activity.AccountDetailsActivity;
import com.dn.lotte.ui.usercenter.activity.AgencyActivity;
import com.dn.lotte.ui.usercenter.activity.BettingActivity;
import com.dn.lotte.ui.usercenter.activity.LoginActivity;
import com.dn.lotte.ui.usercenter.activity.MessageActivity;
import com.dn.lotte.ui.usercenter.activity.NumberRecordActivity;
import com.dn.lotte.ui.usercenter.activity.PersonageActivity;
import com.dn.lotte.ui.usercenter.activity.SettingActivity;
import com.dn.lotte.ui.usercenter.activity.Top_up_recharge_Activity;
import com.dn.lotte.ui.usercenter.activity.WithdrawalActivity;
import com.easy.common.base.BaseFragment;
import com.easy.common.commonwidget.RippleView;
import com.makeramen.roundedimageview.RoundedImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.Bind;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


/**
 * 个人中心
 */
public class UsercenterFragment extends BaseFragment implements RippleView.OnRippleCompleteListener {

    @Bind(R.id.myfragment_iv_back)
    ImageView myfragmentIvBack;
    @Bind(R.id.myfragment_tv_title)
    TextView myfragmentTvTitle;
    @Bind(R.id.myfragment_iv_set)
    ImageView myfragmentIvSet;
    @Bind(R.id.iv_user_head)
    RoundedImageView ivUserHead;
    @Bind(R.id.myfragment_tv_money)
    TextView myfragmentTvMoney;
    @Bind(R.id.myfragment_iv_refresh)
    ImageView myfragmentIvRefresh;
    @Bind(R.id.rl_quickly)
    RippleView rlQuickly;
    @Bind(R.id.rl_withdrawals)
    RippleView rlWithdrawals;
    @Bind(R.id.rl_etting)
    RippleView rlEtting;
    @Bind(R.id.iv_user_download)
    RelativeLayout ivUserDownload;
    @Bind(R.id.usercenter_betting)
    RelativeLayout relativeUsercenterDownloadResume;
    @Bind(R.id.iv_user_remark)
    RelativeLayout ivUserRemark;
    @Bind(R.id.relative_usercenter_remark)
    RelativeLayout relativeUsercenterRemark;
    @Bind(R.id.iv_user_vip)
    RelativeLayout ivUserVip;
    @Bind(R.id.relative_usercenter_vip)
    RelativeLayout relativeUsercenterVip;
    @Bind(R.id.iv_user_info)
    RelativeLayout ivUserInfo;
    @Bind(R.id.relative_usercenter_info)
    RelativeLayout relativeUsercenterInfo;
    @Bind(R.id.iv_user_agency)
    RelativeLayout ivUserAgency;
    @Bind(R.id.relative_usercenter_agency)
    RelativeLayout relativeUsercenterAgency;
    @Bind(R.id.iv_user_mesage)
    RelativeLayout ivUserMesage;
    @Bind(R.id.relative_usercenter_message)
    RelativeLayout relativeUsercenterMessage;
    @Bind(R.id.iv_user_account_setting)
    RelativeLayout ivUserAccountSetting;
    @Bind(R.id.relative_usercenter_set)
    RelativeLayout relativeUsercenterSet;
    @Bind(R.id.iv_user_service)
    RelativeLayout ivUserService;
    @Bind(R.id.relative_usercenter_service)
    RelativeLayout relativeUsercenterService;
    @Bind(R.id.okBtn)
    RippleView okBtn;
    private Intent intent;
    private Animation operatingAnim;
    private String kefuurl = "";
    private int runCount;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_usercenter;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (GlobalApplication.getInstance().getUserModel()!=null&&GlobalApplication.getInstance().getUserModel().getTable()!=null&&GlobalApplication.getInstance().getUserModel().getTable().get(0)!=null){
            myfragmentTvTitle.setText(GlobalApplication.getInstance().getUserModel().getTable().get(0).getUsername());
            myfragmentTvMoney.setText(GlobalApplication.getInstance().getUserModel().getTable().get(0).getMoney());
        }
        initOnclick();
        operatingAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_refesh);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
        loadKeFu();
        getMoney();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //客服地址
    private void loadKeFu() {
        UserCenterServerApi.loadkefu()
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<KefuBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onNext(@NonNull KefuBean kefuBean) {
                        stopProgressDialog();
                        if (kefuBean.getResult().equals("1")) {
                            kefuurl = kefuBean.getTable().get(0).getServiceurl();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();

                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();

                    }
                });
    }

    private void initOnclick() {
        rlQuickly.setOnRippleCompleteListener(this);//充值
        rlWithdrawals.setOnRippleCompleteListener(this);
        rlEtting.setOnRippleCompleteListener(this);
        okBtn.setOnRippleCompleteListener(this);
    }

    @OnClick({R.id.myfragment_iv_set, R.id.relative_usercenter_info,
            R.id.myfragment_iv_refresh, R.id.relative_usercenter_set,
            R.id.relative_usercenter_agency, R.id.usercenter_betting, R.id.relative_usercenter_remark,
            R.id.relative_usercenter_vip, R.id.relative_usercenter_message, R.id.relative_usercenter_service})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.myfragment_iv_set://设置
                intent = new Intent(getActivity(), SettingActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
                break;
            case R.id.usercenter_betting://投注记录
                startActivity(BettingActivity.class);
                break;
            case R.id.relative_usercenter_remark://追号记录
                startActivity(NumberRecordActivity.class);
                break;
            case R.id.relative_usercenter_vip://个人报表
                startActivity(PersonageActivity.class);
                break;
            case R.id.relative_usercenter_info://资金明细
                startActivity(AccountDetailsActivity.class);
                break;
            case R.id.relative_usercenter_agency://代理管理
                intent = new Intent(getActivity(), AgencyActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
                break;
            case R.id.relative_usercenter_message://我的消息
                startActivity(MessageActivity.class);
                break;
            case R.id.relative_usercenter_set://账户设置
                intent = new Intent(getActivity(), SettingActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
                break;
            case R.id.myfragment_iv_refresh://刷新
                if (operatingAnim != null) {
                    myfragmentIvRefresh.startAnimation(operatingAnim);
                    requestMoney();
                }
                break;
            case R.id.relative_usercenter_service://客服
                if (!kefuurl.equals("")) {
                    Uri uri = Uri.parse(kefuurl);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                  /*  Intent intent = new Intent(getActivity(), KeFuActivity.class);
                    intent.putExtra("url", kefuurl);
                    startActivity(intent);*/
                } else {
                    loadKeFu();
                }
                break;


        }
    }

    @Override
    public void onComplete(RippleView rippleView) {
        switch (rippleView.getId()) {
            case R.id.rl_quickly://充值
                intent = new Intent(getActivity(), Top_up_recharge_Activity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
                break;
            case R.id.rl_withdrawals://提现
                intent = new Intent(getActivity(), WithdrawalActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
                break;
            case R.id.rl_etting://账户明细
                startActivity(AccountActivity.class);
                break;
            case R.id.okBtn:
                getcancellation();
                break;
        }
    }

    public void getcancellation() {
        UserCenterServerApi.cancellation()
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SetSafequesBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onNext(@NonNull SetSafequesBean recordStateBean) {
                        stopProgressDialog();
                        showShortToast(recordStateBean.getReturnval());
                        startActivity(LoginActivity.class);
                        getActivity().finish();

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainEventBus(EventBusBean<String> bean) {
        if ("TiXianSuccess".equals(bean.getTag())) {//提现页发过来的消息
            requestMoney();
        }
    }

    public void getMoney() {
        final Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
// TODO Auto-generated method stub
// 在此处添加执行的代码
                Log.e("kdkkd", "dkkdkd");
                requestMoney();
                handler.postDelayed(this, 20000);// 50是延时时长
            }
        };
        handler.postDelayed(runnable, 20000);// 打开定时器，执行操作
        // handler.removeCallbacks(runnable);// 关闭定时器处理
    }

    private void requestMoney() {
        UserCenterServerApi.getMoney()
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<TimeBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onNext(@NonNull TimeBean timeBean) {
                        stopProgressDialog();
                        if (myfragmentTvMoney != null) {
                            myfragmentTvMoney.setText(timeBean.getMoney());
                        }
                        if (myfragmentIvRefresh!=null) {
                            myfragmentIvRefresh.clearAnimation();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();

                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();

                    }
                });
    }
}
